<?php

namespace App\Http\Controllers\Admin;

use App\Models\Permission;
use App\Models\Role;
use App\Models\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Cache;

class AuthController extends Controller
{
    function admin_list()
    {
        //DB::connection()->enableQueryLog();
        $admins = Admin::with('roles')->orderBy('id', 'desc')->paginate(config('page.page_size'));
        //$queries = DB::getQueryLog();
        //$a = end($queries);
        //$tmp = str_replace('?', '"'.'%s'.'"', $a["query"]);
        //echo vsprintf($tmp, $a['bindings']); exit;
        return view('admin.auth.admin_list', compact('admins'));
    }

    function admin_create()
    {
        $roles = Role::all();
        return view('admin.auth.admin_create',compact('roles'));
    }

    function admin_store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:admins',
            'password' => 'required|string|min:6',
        ]);

        $data['name'] = $request->name;
        $data['email'] = $request->email;
        $data['password'] = bcrypt($request->password);
        //$data['remember_token'] = Str::random(60);
        DB::beginTransaction();
        try{
            $admin = Admin::create($data);
            $admin->roles()->sync($request->role_id);
        }catch (\Exception $e){
            DB::rollback();
            return back()->with('alert', '新增用户失败！');
        }
        DB::commit();
        return redirect(route('auth.admin_list'))->with('notice', '新增用户成功！');
    }

    function admin_edit($id)
    {
        $admin = Admin::with('roles')->find($id);
        //return $admin;
        $roles = Role::all();
        return view('admin.auth.admin_edit', compact('admin','roles'));
    }

    function admin_update(Request $request, $id)
    {
        $this->validate($request, [
            'name' => 'required|string|max:255',
            'password' => 'required|string|min:6',
        ]);
        $admin = Admin::find($id);
        $admin->name = $request->name;
        $admin->password = bcrypt($request->password);

        DB::beginTransaction();
        try {
            $admin->roles()->sync($request->role_id);
            $admin->save();
        }catch (\Exception $e) {
            //echo $e->getMessage();
            DB::rollback();
            return back()->with('alert', '更新用户失败！');
            //$data['status'] = 0;
            //$data['info'] = $e->getMessage();
            //return $data;
        }
        DB::commit();
        return redirect(route('auth.admin_list'))->with('notice', '更新用户成功!');
    }

    function admin_destroy($id)
    {
        if (Auth::id() == $id) {
            return back()->with('alert', '不能删除自己！');
        }
        DB::beginTransaction();
        $admin = Admin::find($id);
        try{
            $admin->delete();
            $admin->roles()->sync([]);
        }catch (\Exception $e){
            DB::rollback();
            return back()->with('alert', '删除用户失败！');
        }
        DB::commit();
        return redirect(route('auth.admin_list'))->with('notice', '删除用户成功!');
    }

    function role_list(){
        $roles = Role::orderBy('id', 'desc')->paginate(config('page.page_size'));
        return view('admin.auth.role_list', compact('roles'));
    }

    function role_create(){
        $permissions = Permission::where('pid',0)->with('children')->get();
        //return $permissions;
        return view('admin.auth.role_create',compact('permissions'));
    }

    function role_store(Request $request){
        $this->validate($request, [
            'name' => 'required|string|max:255|unique:roles',
            'label' => 'required|string|max:255|unique:roles',
        ]);
        DB::beginTransaction();
        try{
            $role = Role::create(collect($request)->forget(['permission_id'])->all());
            $role->permissions()->sync($request->permission_id);
        }catch (\Exception $e){
            DB::rollback();
            return back()->with('alert', '新增用色失败！');
        }
        DB::commit();
        return redirect(route('auth.role_list'))->with('notice', '新增角色成功！');
    }

    function role_edit($id){
        $role = Role::with('permissions')->find($id);
        $permissions = Permission::where('pid',0)->with('children')->get();
        return view('admin.auth.role_edit',compact('role','permissions'));
    }

    function role_update(Request $request,$id){
        /*$this->validate($request, [
            'name' => 'required|string|max:255|unique:roles',
            'label' => 'required|string|max:255|unique:roles',
        ]);*/
        $role = Role::find($id);
        DB::beginTransaction();
        try{
            $role->update(collect($request)->forget(['permission_id'])->all());
            $role->permissions()->sync($request->permission_id);
        }catch (\Exception $e){
            DB::rollback();
            return back()->with('alert', '更新角色失败！');
        }
        DB::commit();
        return redirect(route('auth.role_list'))->with('notice', '更新角色成功！');
        /*if($role->update($request->all())){
            return redirect(route('auth.role_list'))->with('notice', '更新角色成功！');
        }else
            return back()->with('alert', '更新角色失败！');*/
    }

    function role_destroy($id){
        //当有用户属于当角色时不能删除
        $role = Role::with('admins')->where('id',$id)->first();
        if(count($role->admins->pluck('id'))){
            return back()->with('alert', '有用户属于该角色，删除角色失败！');
        }else{
            if($role->delete()){
                return redirect(route('auth.role_list'))->with('notice', '删除角色成功！');
            }else
                return back()->with('alert', '删除角色失败！');
        }
    }

    function permission_list(){
        $res = Permission::orderBy('id','desc')->get();
        $res = tree($res);
        //获取当前的分页数，就是这样的
        $currentPage = LengthAwarePaginator::resolveCurrentPage();
        //实例化collect方法
        $collection = new Collection($res);
        //定义一下每页显示多少个数据
        //$perPage = config('page.page_size');
        $perPage = 10;
        //获取当前需要显示的数据列表
        $currentPageSearchResults = $collection->slice(($currentPage-1) * $perPage, $perPage)->all();
        //创建一个新的分页方法
        $permissions= new LengthAwarePaginator($currentPageSearchResults, count($collection), $perPage);
        //return $permissions;
        //return $name = Route::currentRouteName();
        //dump(route(Route::currentRouteName()));exit;
        $permissions->withPath(route(Route::currentRouteName()));
        //return $permissions;
        return view('admin.auth.permission_list', compact('permissions'));
    }

    function permission_create(){
        $top_permissions = Permission::where('pid',0)->get();
        return view('admin.auth.permission_create', compact('top_permissions'));
    }

    function permission_store(Request $request){
        $this->validate($request, [
            'name' => 'required|string|max:255|unique:permissions',
            'label' => 'required|string|max:255|unique:permissions',
        ]);
        Permission::create($request->all());
        return redirect(route('auth.permission_list'))->with('notice', '新增权限成功！');
    }

    function permission_edit($id){
        $permission = Permission::find($id);
        $top_permissions = Permission::where('pid',0)->get();
        return view('admin.auth.permission_edit', compact('top_permissions','permission'));
    }

    function permission_update(Request $request,$id){
        $this->validate($request, [
            'name' => 'required|string|max:255',
            'label' => 'required|string|max:255',
        ]);
        $permission = Permission::find($id);
        $permission->update($request->all());
        return redirect(route('auth.permission_list'))->with('notice', '更新权限成功！');
    }

    function permission_destroy($id){
        $permission = Permission::find($id);
        if(count($permission->children)){
            return back()->with('alert', '此权限有下级，删除权限失败！');
        }
        $permission->delete();
        return redirect(route('auth.permission_list'))->with('notice', '删除权限成功！');
    }

    function clear_cache(){
        Cache::flush();
        return back()->with('notice', '缓存清除成功~');
    }
}


